package org.janzen_zhang.androidftp;

import android.Manifest;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.TextViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.SwitchCompat;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;

public class MainActivity extends AppCompatActivity {
    private final String TAG = "MainActivity";

    private SwitchCompat mSwitchCompat;

    private AppCompatTextView mStatusTextView;

    private String addressString;

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            FTPService.FTPBinder binder = (FTPService.FTPBinder) service;
            FTPService ftpService = binder.getService();
            addressString = ftpService.getIpAndHost();
            if (mStatusTextView != null) {
                String ftpString = getString(R.string.ftpString, addressString);
                mStatusTextView.setText(getString(R.string.current_status, ftpString));
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }

    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mStatusTextView = (AppCompatTextView) findViewById(R.id.currentStatus);
        mSwitchCompat = (SwitchCompat) findViewById(R.id.switchBtn);

        mSwitchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        if (hasExternalStoragePermission(MainActivity.this)) {
                            if (isWifiConnected(MainActivity.this)) {
                                Intent intent = new Intent(MainActivity.this, FTPService.class);
                                bindService(intent, serviceConnection, BIND_AUTO_CREATE);
                            } else {
                                Snackbar.make(mStatusTextView, R.string.wifi_disconnect, Snackbar.LENGTH_LONG).show();
                                buttonView.setChecked(false);
                            }
                        }
                    } else {
                        if (isWifiConnected(MainActivity.this)) {
                            Intent intent = new Intent(MainActivity.this, FTPService.class);
                            bindService(intent, serviceConnection, BIND_AUTO_CREATE);
                        } else {
                            Snackbar.make(mStatusTextView, R.string.wifi_disconnect, Snackbar.LENGTH_LONG).show();
                            buttonView.setChecked(false);
                        }
                    }
                } else {
                    unbindService(serviceConnection);

                    if (mStatusTextView != null) {
                        mStatusTextView.setText(R.string.tip);
                    }
                    if (!hasExternalStoragePermission(MainActivity.this)) {
                        Snackbar.make(mStatusTextView, R.string.no_permission, Snackbar.LENGTH_LONG).show();
                    }
                }

            }
        });

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE},0);
        }

        mStatusTextView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (!mStatusTextView.getText().toString().isEmpty()) {
                    onLongClickCopy(getString(R.string.ftpString, addressString));
                }
                return true;
            }
        });
    }

    public void onLongClickCopy(String text) {
        // 从API11开始android推荐使用android.content.ClipboardManager
        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        // 将文本内容放到系统剪贴板里。
        ClipData clipData = ClipData.newPlainText("text", text);
        cm.setPrimaryClip(clipData);
        Snackbar.make(mStatusTextView, R.string.copy_tip, Snackbar.LENGTH_LONG).show();
    }

    private static boolean hasExternalStoragePermission(Context context) {
        int writePermission = context.checkCallingOrSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        int readPermission = context.checkCallingPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
        return writePermission == PackageManager.PERMISSION_GRANTED /*&& readPermission == PackageManager.PERMISSION_GRANTED*/;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 0) {

        }
    }

    public static boolean isWifiConnected(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifiNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if(wifiNetworkInfo.isConnected()) {
            return true ;
        }

        return false ;
    }

}
